<template>
  <el-dialog v-model="visible" title="登录" :width="500" :append-to-body="true" :draggable="true" :before-close="handleClose">
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large" class="login-form px-10 py-1" label-position="left">
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入用户名" type="text">
          <template #prepend>
            <i-carbon-user />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" :maxlength="16" show-password placeholder="请输入密码" @keyup.native="handleLogin(loginFormRef)">
          <template #prepend>
            <i-carbon-password />
          </template>
        </el-input>
      </el-form-item>
      <el-button :loading="loading" type="success" class="login-btn w-full" round @click.prevent="handleLogin(loginFormRef)">登录</el-button>
      <div class="mt-6 flex justify-between">
        <el-button type="primary" text>找回密码</el-button>
        <el-button type="primary" text>注册</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { set } from '@vueuse/core'
import useMemberStore from '@/store/modules/member'

interface EditProps {
  setEditVisible: any
  title?: string
}

const props = withDefaults(defineProps<EditProps>(), {
  editVisible: false,
  title: '',
  columns: [],
  setEditVisible: () => {},
})

const loading = ref(false)
const visible = ref(true)
const loginFormRef = ref<FormInstance>()
const memberStore = useMemberStore()

// 验证规则
const loginRules = reactive<FormRules>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

// Form字段
const loginForm = reactive({
  username: 'admin',
  password: 'admin123456',
})

// 关闭
const handleClose = () => {
  props.setEditVisible()
}

// 处理登录
const handleLogin = (loginFormRef: FormInstance | undefined) => {
  set(loading, true)

  loginFormRef
    .validate((isValid) => {
      if (!isValid) return

      memberStore
        .login(loginForm)
        .then(() => {
          navigateTo('/member/home')
          set(loading, false)
        })
        .catch(() => {
          set(loading, false)
        })
    })
    .finally(() => {
      handleClose()
      setTimeout(() => {
        set(loading, false)
      }, 500)
    })
}
</script>
